<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件监控应用</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                        danger: '#ef4444',
                        warning: '#f59e0b',
                        info: '#06b6d4',
                        dark: '#1e293b',
                        light: '#f8fafc'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <div class="min-h-screen flex flex-col">
        <!-- 导航栏 -->
        <nav class="bg-white shadow-md">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 flex items-center">
                            <i class="fa fa-file-text-o text-primary text-2xl mr-2"></i>
                            <span class="font-bold text-xl text-dark">文件监控应用</span>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <button id="refresh-btn" class="mr-4 text-gray-600 hover:text-primary transition-all-300">
                            <i class="fa fa-refresh"></i>
                            <span class="ml-1">刷新</span>
                        </button>
                        <button id="add-task-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-md transition-all-300">
                            <i class="fa fa-plus mr-1"></i>
                            <span>创建任务</span>
                        </button>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 主要内容 -->
        <main class="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6">
            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div class="bg-white rounded-lg p-6 shadow-lg transition-all duration-300 hover:shadow-xl">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">总任务数</p>
                            <h3 id="total-tasks" class="text-3xl font-bold text-dark mt-1">0</h3>
                        </div>
                        <div class="bg-blue-100 p-3 rounded-full">
                            <i class="fa fa-tasks text-primary text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 flex items-center">
                        <span id="running-tasks" class="text-secondary flex items-center">
                            <i class="fa fa-play-circle mr-1"></i> 运行中: 0
                        </span>
                        <span id="stopped-tasks" class="text-gray-500 flex items-center ml-4">
                            <i class="fa fa-pause-circle mr-1"></i> 已停止: 0
                        </span>
                    </div>
                </div>

                <div class="bg-white rounded-lg p-6 shadow-lg transition-all duration-300 hover:shadow-xl">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">总传输文件</p>
                            <h3 id="total-files" class="text-3xl font-bold text-dark mt-1">0</h3>
                        </div>
                        <div class="bg-green-100 p-3 rounded-full">
                            <i class="fa fa-exchange text-secondary text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="flex justify-between text-sm mb-1">
                            <span class="text-gray-500">成功</span>
                            <span id="success-files" class="text-secondary font-medium">0</span>
                        </div>
                        <div class="flex justify-between text-sm mb-1">
                            <span class="text-gray-500">失败</span>
                            <span id="failed-files" class="text-danger font-medium">0</span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                            <div id="success-rate" class="bg-secondary h-2.5 rounded-full" style="width: 0%"></div>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg p-6 shadow-lg transition-all duration-300 hover:shadow-xl">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">传输成功率</p>
                            <h3 id="success-rate-text" class="text-3xl font-bold text-dark mt-1">0%</h3>
                        </div>
                        <div class="bg-purple-100 p-3 rounded-full">
                            <i class="fa fa-line-chart text-purple-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <canvas id="success-chart" width="400" height="100"></canvas>
                    </div>
                </div>
            </div>

            <!-- 任务列表 -->
            <div class="bg-white rounded-lg shadow-lg mb-8">
                <div class="flex justify-between items-center p-6 border-b">
                    <h2 class="text-xl font-bold text-dark">任务列表</h2>
                    <div class="relative">
                        <input type="text" id="search-task" placeholder="搜索任务..." class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">源目录</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">目标类型</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">扫描间隔(秒)</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="task-list" class="bg-white divide-y divide-gray-200">
                            <!-- 任务行将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
                <div id="empty-task" class="p-6 text-center text-gray-500 hidden">
                    <i class="fa fa-folder-open-o text-4xl mb-2 text-gray-300"></i>
                    <p>暂无任务，请点击右上角"创建任务"按钮添加</p>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="bg-white border-t border-gray-200 py-4">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <p class="text-center text-gray-500 text-sm">
                    &copy; 2025 文件监控应用 - 实时监控和传输文件
                </p>
            </div>
        </footer>
    </div>

    <!-- 创建/编辑任务模态框 -->
    <div id="task-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 transform transition-all">
            <div class="flex justify-between items-center p-6 border-b">
                <h3 id="modal-title" class="text-lg font-bold text-dark">创建任务</h3>
                <button id="close-modal" class="text-gray-400 hover:text-gray-500">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <form id="task-form">
                    <input type="hidden" id="task-id" value="">
                    
                    <div class="mb-4">
                        <label for="task-name" class="block text-sm font-medium text-gray-700 mb-1">任务名称</label>
                        <input type="text" id="task-name" name="name" required class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    
                    <div class="mb-4">
                        <label for="source-dir" class="block text-sm font-medium text-gray-700 mb-1">源目录</label>
                        <input type="text" id="source-dir" name="source_dir" required class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="dest-type" class="block text-sm font-medium text-gray-700 mb-1">目标类型</label>
                            <select id="dest-type" name="dest_type" required class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                                <option value="local">本地目录</option>
                                <option value="ftp">FTP服务器</option>
                            </select>
                        </div>
                        
                        <div id="dest-path-container">
                            <label for="dest-path" class="block text-sm font-medium text-gray-700 mb-1">目标路径</label>
                            <input type="text" id="dest-path" name="dest_path" required class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="输入本地目录路径">
                        </div>
                    </div>
                    
                    <div id="ftp-options" class="hidden mb-4 p-4 bg-gray-50 rounded-md">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="ftp-host" class="block text-sm font-medium text-gray-700 mb-1">主机</label>
                                <input type="text" id="ftp-host" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                            </div>
                            <div>
                                <label for="ftp-port" class="block text-sm font-medium text-gray-700 mb-1">端口</label>
                                <input type="number" id="ftp-port" value="21" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                            </div>
                            <div>
                                <label for="ftp-user" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                <input type="text" id="ftp-user" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                            </div>
                            <div>
                                <label for="ftp-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                                <input type="password" id="ftp-password" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                            </div>
                            <div>
                                <label for="ftp-dir" class="block text-sm font-medium text-gray-700 mb-1">远程目录</label>
                                <input type="text" id="ftp-dir" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="file-types" class="block text-sm font-medium text-gray-700 mb-1">文件类型(逗号分隔)</label>
                            <input type="text" id="file-types" name="file_types" placeholder="例如: .jpg,.png,.txt" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                        </div>
                        <div>
                            <label for="scan-interval" class="block text-sm font-medium text-gray-700 mb-1">扫描间隔(秒)</label>
                            <input type="number" id="scan-interval" name="scan_interval" value="60" min="1" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label for="max-retries" class="block text-sm font-medium text-gray-700 mb-1">最大重试次数</label>
                        <input type="number" id="max-retries" name="max_retries" value="3" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                    </div>
                    
                    <div class="flex justify-end pt-4 border-t">
                        <button type="button" id="cancel-task" class="mr-3 px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-all-300">取消</button>
                        <button type="submit" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-md transition-all-300">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 任务详情模态框 -->
    <div id="task-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 transform transition-all max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center p-6 border-b">
                <h3 id="detail-modal-title" class="text-lg font-bold text-dark">任务详情</h3>
                <button id="close-detail-modal" class="text-gray-400 hover:text-gray-500">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-2">基本信息</h4>
                        <div class="bg-gray-50 rounded-lg p-4">
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">任务名称:</span>
                                <span id="detail-name" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">源目录:</span>
                                <span id="detail-source-dir" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">目标类型:</span>
                                <span id="detail-dest-type" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">目标路径:</span>
                                <span id="detail-dest-path" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">文件类型:</span>
                                <span id="detail-file-types" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">扫描间隔:</span>
                                <span id="detail-scan-interval" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div>
                                <span class="text-sm text-gray-500">最大重试次数:</span>
                                <span id="detail-max-retries" class="text-dark font-medium ml-2"></span>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-2">统计信息</h4>
                        <div class="bg-gray-50 rounded-lg p-4">
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">总传输文件:</span>
                                <span id="detail-total-files" class="text-dark font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">成功文件:</span>
                                <span id="detail-success-files" class="text-secondary font-medium ml-2"></span>
                            </div>
                            <div class="mb-3">
                                <span class="text-sm text-gray-500">失败文件:</span>
                                <span id="detail-failed-files" class="text-danger font-medium ml-2"></span>
                            </div>
                            <div>
                                <span class="text-sm text-gray-500">成功率:</span>
                                <span id="detail-success-rate" class="text-dark font-medium ml-2"></span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div>
                    <h4 class="text-sm font-medium text-gray-500 mb-2">最近传输记录</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件路径</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">尝试次数</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">错误信息</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">开始时间</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">完成时间</th>
                                </tr>
                            </thead>
                            <tbody id="detail-transfers" class="bg-white divide-y divide-gray-200">
                                <!-- 传输记录将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                    <div id="empty-transfers" class="p-6 text-center text-gray-500 hidden">
                        <p>暂无传输记录</p>
                    </div>
                </div>
            </div>
            <div class="p-6 border-t flex justify-end">
                <button id="close-detail-btn" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-md transition-all-300">关闭</button>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        let successChart;
        
        // DOM元素
        const taskList = document.getElementById('task-list');
        const emptyTask = document.getElementById('empty-task');
        const addTaskBtn = document.getElementById('add-task-btn');
        const taskModal = document.getElementById('task-modal');
        const closeModal = document.getElementById('close-modal');
        const cancelTask = document.getElementById('cancel-task');
        const taskForm = document.getElementById('task-form');
        const modalTitle = document.getElementById('modal-title');
        const destType = document.getElementById('dest-type');
        const destPath = document.getElementById('dest-path');
        const ftpOptions = document.getElementById('ftp-options');
        const ftpHost = document.getElementById('ftp-host');
        const ftpPort = document.getElementById('ftp-port');
        const ftpUser = document.getElementById('ftp-user');
        const ftpPassword = document.getElementById('ftp-password');
        const ftpDir = document.getElementById('ftp-dir');
        const refreshBtn = document.getElementById('refresh-btn');
        const searchTask = document.getElementById('search-task');
        const taskDetailModal = document.getElementById('task-detail-modal');
        const closeDetailModal = document.getElementById('close-detail-modal');
        const closeDetailBtn = document.getElementById('close-detail-btn');
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图表
            const ctx = document.getElementById('success-chart').getContext('2d');
            successChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['成功', '失败'],
                    datasets: [{
                        data: [0, 0],
                        backgroundColor: [
                            '#10b981',
                            '#ef4444'
                        ],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
            
            // 加载任务列表
            loadTasks();
            
            // 加载统计信息
            loadStats();
            
            // 事件监听
            addTaskBtn.addEventListener('click', openCreateTaskModal);
            closeModal.addEventListener('click', closeTaskModal);
            cancelTask.addEventListener('click', closeTaskModal);
            taskForm.addEventListener('submit', handleTaskFormSubmit);
            destType.addEventListener('change', toggleDestOptions);
            refreshBtn.addEventListener('click', refreshData);
            searchTask.addEventListener('input', filterTasks);
            closeDetailModal.addEventListener('click', closeDetailModalFunc);
            closeDetailBtn.addEventListener('click', closeDetailModalFunc);
        });
        
        // 加载任务列表
        function loadTasks() {
            fetch('/api/tasks')
                .then(response => response.json())
                .then(tasks => {
                    taskList.innerHTML = '';
                    
                    if (tasks.length === 0) {
                        emptyTask.classList.remove('hidden');
                        return;
                    }
                    
                    emptyTask.classList.add('hidden');
                    
                    tasks.forEach(task => {
                        const row = document.createElement('tr');
                        row.className = 'hover:bg-gray-50 transition-all-300';
                        row.dataset.id = task.id;
                        
                        // 格式化目标路径
                        let destPathDisplay = task.dest_path;
                        if (task.dest_type === 'ftp') {
                            try {
                                const ftpInfo = JSON.parse(task.dest_path);
                                destPathDisplay = `${ftpInfo.host}:${ftpInfo.port}/${ftpInfo.remote_dir || ''}`;
                            } catch (e) {
                                destPathDisplay = 'FTP配置错误';
                            }
                        }
                        
                        // 状态标签
                        const statusClass = task.is_running ? 'bg-green-100 text-secondary' : 'bg-gray-100 text-gray-500';
                        const statusText = task.is_running ? '运行中' : '已停止';
                        const statusIcon = task.is_running ? 'fa-play-circle' : 'fa-pause-circle';
                        
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10 bg-blue-100 rounded-full flex items-center justify-center">
                                        <i class="fa fa-folder text-primary"></i>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">${task.name}</div>
                                        <div class="text-sm text-gray-500">
                                            ${task.last_scan ? `上次扫描: ${task.last_scan}` : '未扫描'}
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-900">${task.source_dir}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${task.dest_type === 'local' ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800'}">
                                    ${task.dest_type === 'local' ? '本地目录' : 'FTP服务器'}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                ${task.scan_interval} 秒
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                                    <i class="fa ${statusIcon} mr-1"></i>${statusText}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                ${formatDateTime(task.created_at)}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <button class="view-task mr-2 text-gray-600 hover:text-primary transition-all-300">
                                    <i class="fa fa-eye"></i> 查看
                                </button>
                                <button class="edit-task mr-2 text-gray-600 hover:text-primary transition-all-300">
                                    <i class="fa fa-pencil"></i> 编辑
                                </button>
                                ${task.is_running ? 
                                    `<button class="stop-task mr-2 text-gray-600 hover:text-danger transition-all-300">
                                        <i class="fa fa-pause"></i> 停止
                                    </button>` : 
                                    `<button class="start-task mr-2 text-gray-600 hover:text-secondary transition-all-300">
                                        <i class="fa fa-play"></i> 启动
                                    </button>`
                                }
                                <button class="delete-task text-gray-600 hover:text-danger transition-all-300">
                                    <i class="fa fa-trash"></i> 删除
                                </button>
                            </td>
                        `;
                        
                        taskList.appendChild(row);
                        
                        // 添加事件监听
                        row.querySelector('.view-task').addEventListener('click', () => viewTask(task.id));
                        row.querySelector('.edit-task').addEventListener('click', () => editTask(task.id));
                        row.querySelector('.start-task').addEventListener('click', () => startTask(task.id));
                        row.querySelector('.stop-task').addEventListener('click', () => stopTask(task.id));
                        row.querySelector('.delete-task').addEventListener('click', () => deleteTask(task.id));
                    });
                })
                .catch(error => {
                    console.error('Error loading tasks:', error);
                    showNotification('加载任务失败', 'error');
                });
        }
        
        // 加载统计信息
        function loadStats() {
            fetch('/api/stats')
                .then(response => response.json())
                .then(stats => {
                    // 更新统计卡片
                    document.getElementById('total-tasks').textContent = stats.total_tasks;
                    document.getElementById('running-tasks').innerHTML = `<i class="fa fa-play-circle mr-1"></i> 运行中: ${stats.running_tasks}`;
                    document.getElementById('stopped-tasks').innerHTML = `<i class="fa fa-pause-circle mr-1"></i> 已停止: ${stats.stopped_tasks}`;
                    document.getElementById('total-files').textContent = stats.total_files;
                    document.getElementById('success-files').textContent = stats.success_files;
                    document.getElementById('failed-files').textContent = stats.failed_files;
                    document.getElementById('success-rate').style.width = `${stats.success_rate}%`;
                    document.getElementById('success-rate-text').textContent = `${stats.success_rate.toFixed(1)}%`;
                    
                    // 更新图表
                    successChart.data.datasets[0].data = [stats.success_files, stats.failed_files];
                    successChart.update();
                })
                .catch(error => {
                    console.error('Error loading stats:', error);
                    showNotification('加载统计信息失败', 'error');
                });
        }
        
        // 打开创建任务模态框
        function openCreateTaskModal() {
            modalTitle.textContent = '创建任务';
            document.getElementById('task-id').value = '';
            taskForm.reset();
            destType.value = 'local';
            toggleDestOptions();
            taskModal.classList.remove('hidden');
        }
        
        // 关闭任务模态框
        function closeTaskModal() {
            taskModal.classList.add('hidden');
        }
        
        // 处理任务表单提交
        function handleTaskFormSubmit(e) {
            e.preventDefault();
            
            const taskId = document.getElementById('task-id').value;
            const formData = {
                name: document.getElementById('task-name').value,
                source_dir: document.getElementById('source-dir').value,
                dest_type: destType.value,
                dest_path: destType.value === 'local' ? 
                    document.getElementById('dest-path').value : 
                    JSON.stringify({
                        host: ftpHost.value,
                        port: ftpPort.value,
                        user: ftpUser.value,
                        password: ftpPassword.value,
                        remote_dir: ftpDir.value
                    }),
                file_types: document.getElementById('file-types').value,
                scan_interval: parseInt(document.getElementById('scan-interval').value),
                max_retries: parseInt(document.getElementById('max-retries').value),
                status: taskId ? (document.querySelector(`tr[data-id="${taskId}"] .stop-task`) ? 'running' : 'stopped') : 'stopped'
            };
            
            const url = taskId ? `/api/tasks/${taskId}` : '/api/tasks';
            const method = taskId ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                showNotification(taskId ? '任务更新成功' : '任务创建成功', 'success');
                closeTaskModal();
                loadTasks();
                loadStats();
            })
            .catch(error => {
                console.error('Error submitting form:', error);
                showNotification(taskId ? '更新任务失败' : '创建任务失败', 'error');
            });
        }
        
        // 切换目标选项
        function toggleDestOptions() {
            if (destType.value === 'ftp') {
                destPath.placeholder = '将自动填充为FTP配置';
                ftpOptions.classList.remove('hidden');
                
                // 尝试解析现有FTP配置
                if (destPath.value) {
                    try {
                        const ftpInfo = JSON.parse(destPath.value);
                        ftpHost.value = ftpInfo.host || '';
                        ftpPort.value = ftpInfo.port || 21;
                        ftpUser.value = ftpInfo.user || '';
                        ftpPassword.value = ftpInfo.password || '';
                        ftpDir.value = ftpInfo.remote_dir || '';
                    } catch (e) {
                        // 忽略解析错误
                    }
                }
            } else {
                destPath.placeholder = '输入本地目录路径';
                ftpOptions.classList.add('hidden');
            }
        }
        
        // 编辑任务
        function editTask(taskId) {
            fetch(`/api/tasks/${taskId}`)
                .then(response => response.json())
                .then(task => {
                    modalTitle.textContent = '编辑任务';
                    document.getElementById('task-id').value = task.id;
                    document.getElementById('task-name').value = task.name;
                    document.getElementById('source-dir').value = task.source_dir;
                    destType.value = task.dest_type;
                    
                    if (task.dest_type === 'ftp') {
                        try {
                            const ftpInfo = JSON.parse(task.dest_path);
                            ftpHost.value = ftpInfo.host || '';
                            ftpPort.value = ftpInfo.port || 21;
                            ftpUser.value = ftpInfo.user || '';
                            ftpPassword.value = ftpInfo.password || '';
                            ftpDir.value = ftpInfo.remote_dir || '';
                        } catch (e) {
                            // 忽略解析错误
                        }
                    } else {
                        destPath.value = task.dest_path;
                    }
                    
                    document.getElementById('file-types').value = task.file_types;
                    document.getElementById('scan-interval').value = task.scan_interval;
                    document.getElementById('max-retries').value = task.max_retries;
                    
                    toggleDestOptions();
                    taskModal.classList.remove('hidden');
                })
                .catch(error => {
                    console.error('Error loading task:', error);
                    showNotification('加载任务失败', 'error');
                });
        }
        
        // 启动任务
        function startTask(taskId) {
            if (!confirm('确定要启动这个任务吗？')) {
                return;
            }
            
            fetch(`/api/tasks/${taskId}/start`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                showNotification('任务已启动', 'success');
                loadTasks();
            })
            .catch(error => {
                console.error('Error starting task:', error);
                showNotification('启动任务失败', 'error');
            });
        }
        
        // 停止任务
        function stopTask(taskId) {
            if (!confirm('确定要停止这个任务吗？')) {
                return;
            }
            
            fetch(`/api/tasks/${taskId}/stop`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                showNotification('任务已停止', 'success');
                loadTasks();
            })
            .catch(error => {
                console.error('Error stopping task:', error);
                showNotification('停止任务失败', 'error');
            });
        }
        
        // 删除任务
        function deleteTask(taskId) {
            if (!confirm('确定要删除这个任务吗？这将删除所有相关的传输记录！')) {
                return;
            }
            
            fetch(`/api/tasks/${taskId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                showNotification('任务已删除', 'success');
                loadTasks();
                loadStats();
            })
            .catch(error => {
                console.error('Error deleting task:', error);
                showNotification('删除任务失败', 'error');
            });
        }
        
        // 查看任务详情
        function viewTask(taskId) {
            fetch(`/api/tasks/${taskId}`)
                .then(response => response.json())
                .then(task => {
                    // 填充基本信息
                    document.getElementById('detail-name').textContent = task.name;
                    document.getElementById('detail-source-dir').textContent = task.source_dir;
                    
                    const destTypeText = task.dest_type === 'local' ? '本地目录' : 'FTP服务器';
                    document.getElementById('detail-dest-type').textContent = destTypeText;
                    
                    let destPathDisplay = task.dest_path;
                    if (task.dest_type === 'ftp') {
                        try {
                            const ftpInfo = JSON.parse(task.dest_path);
                            destPathDisplay = `${ftpInfo.host}:${ftpInfo.port}/${ftpInfo.remote_dir || ''}`;
                        } catch (e) {
                            destPathDisplay = 'FTP配置错误';
                        }
                    }
                    document.getElementById('detail-dest-path').textContent = destPathDisplay;
                    
                    document.getElementById('detail-file-types').textContent = task.file_types || '所有文件';
                    document.getElementById('detail-scan-interval').textContent = `${task.scan_interval} 秒`;
                    document.getElementById('detail-max-retries').textContent = task.max_retries;
                    
                    // 加载统计信息
                    fetch(`/api/tasks/${taskId}/stats`)
                        .then(response => response.json())
                        .then(stats => {
                            document.getElementById('detail-total-files').textContent = stats.total_files;
                            document.getElementById('detail-success-files').textContent = stats.success_files;
                            document.getElementById('detail-failed-files').textContent = stats.failed_files;
                            document.getElementById('detail-success-rate').textContent = `${stats.success_rate.toFixed(1)}%`;
                            
                            // 填充传输记录
                            const transfersContainer = document.getElementById('detail-transfers');
                            transfersContainer.innerHTML = '';
                            
                            if (stats.recent_transfers.length === 0) {
                                document.getElementById('empty-transfers').classList.remove('hidden');
                                return;
                            }
                            
                            document.getElementById('empty-transfers').classList.add('hidden');
                            
                            stats.recent_transfers.forEach(transfer => {
                                const row = document.createElement('tr');
                                row.className = 'hover:bg-gray-50 transition-all-300';
                                
                                // 状态样式
                                const statusClass = transfer.status === 'success' ? 'text-secondary' : 'text-danger';
                                const statusIcon = transfer.status === 'success' ? 'fa-check-circle' : 'fa-times-circle';
                                
                                row.innerHTML = `
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900">${transfer.file_path}</div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="text-sm ${statusClass}">
                                            <i class="fa ${statusIcon} mr-1"></i>${transfer.status}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        ${transfer.attempts}
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900">
                                        ${transfer.error || '-'}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        ${formatDateTime(transfer.created_at)}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        ${transfer.completed_at ? formatDateTime(transfer.completed_at) : '-'}
                                    </td>
                                `;
                                
                                transfersContainer.appendChild(row);
                            });
                        })
                        .catch(error => {
                            console.error('Error loading task stats:', error);
                            showNotification('加载任务统计信息失败', 'error');
                        });
                    
                    taskDetailModal.classList.remove('hidden');
                })
                .catch(error => {
                    console.error('Error loading task:', error);
                    showNotification('加载任务失败', 'error');
                });
        }
        
        // 关闭详情模态框
        function closeDetailModalFunc() {
            taskDetailModal.classList.add('hidden');
        }
        
        // 刷新数据
        function refreshData() {
            loadTasks();
            loadStats();
            showNotification('数据已刷新', 'success');
        }
        
        // 过滤任务
        function filterTasks() {
            const searchTerm = searchTask.value.toLowerCase();
            const rows = taskList.querySelectorAll('tr');
            
            rows.forEach(row => {
                const taskName = row.querySelector('td:first-child .text-sm.font-medium').textContent.toLowerCase();
                const sourceDir = row.querySelector('td:nth-child(2) .text-sm').textContent.toLowerCase();
                
                if (taskName.includes(searchTerm) || sourceDir.includes(searchTerm)) {
                    row.classList.remove('hidden');
                } else {
                    row.classList.add('hidden');
                }
            });
        }
        
        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            
            const date = new Date(dateTime);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            // 检查是否已存在通知元素
            let notification = document.querySelector('.notification');
            if (notification) {
                notification.remove();
            }
            
            // 创建通知元素
            notification = document.createElement('div');
            notification.className = `notification fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg transform transition-all duration-500 ease-in-out z-50 ${
                type === 'success' ? 'bg-green-500 text-white' : 
                type === 'error' ? 'bg-red-500 text-white' : 
                'bg-blue-500 text-white'
            }`;
            
            // 设置图标
            const icon = type === 'success' ? 'fa-check-circle' : 
                         type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
            
            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="fa ${icon} mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(notification);
            
            // 动画效果
            setTimeout(() => {
                notification.classList.add('opacity-0', 'translate-y-[-20px]');
                setTimeout(() => {
                    notification.remove();
                }, 500);
            }, 3000);
        }
    </script>
</body>
</html>    